package com.lagou.client;

import com.alibaba.fastjson.JSONObject;
import com.lagou.service.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.I0Itec.zkclient.ZkClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {
    //用来关闭客户端连接
    static SocketChannel socketChannel;
    static Thread thread;
    static String path = "/Server";
    static String ip;
    static Integer port;

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler;

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法

                if(userClientHandler == null){
                 initClient();
                }

                //封装
                RpcRequest request = new RpcRequest();
                String requestId = UUID.randomUUID().toString();
                System.out.println(requestId);

                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();

                Class<?>[] parameterTypes = method.getParameterTypes();

                request.setRequestId(requestId);
                request.setClassName(className);
                request.setMethodName(methodName);
                request.setParameterTypes(parameterTypes);
                request.setParameters(args);



                // 设置参数
                userClientHandler.setPara(request);
                System.out.println(request);
                System.out.println("设置参数完成");

                // 去服务端请求数据

                return executor.submit(userClientHandler).get();
            }
        });


    }



    //2.初始化netty客户端
    public static  void initClient() throws InterruptedException {
         userClientHandler = new UserClientHandler();

        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                        socketChannel=ch;
                    }
                });
        ZkClient zkClient = new ZkClient("192.168.115.129:2181");

        //读取子节点列表，获取可用的服务
        List<String> children = zkClient.getChildren(path);
        Collections.sort(children);
        System.out.println("==="+children);
        /*for(Object ch:children){
            String  c=(String)ch;
        }*/
        if(children!=null && children.size()==1){
            String nn=children.get(0);
            System.out.println(nn);
            Object nodes = zkClient.readData(path+"/"+nn);
            if(nodes!=null){
                JSONObject json=(JSONObject) nodes;
                 ip=json.getString("ip");
                 port=json.getInteger("port");
                System.out.println("开始建立连接"+"ip:"+ip+"port:"+port);
                bootstrap.connect(ip,port).sync();
                System.out.println("连接建立成功");

               // Thread thread=new Thread(new Runnable() {
                 thread=new Thread(new Runnable() {
                    public void run() {
                        try{
                            ZkService.init(socketChannel,thread,ip,port);
                            System.out.println("监听器启动成功...");
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });
                thread.start();


            }

        }


    }







}
